package br.com.ia.test;

import java.util.Hashtable;
import java.util.StringTokenizer;

public class Matcher {

	StringTokenizer st1;
	StringTokenizer st2;
	Hashtable vars;

	Matcher() {
		vars = new Hashtable();
	}

	public boolean matching(String string1, String string2, Hashtable bindings) {
		this.vars = bindings;
		return matching(string1, string2);
	}

	public boolean matching(String string1, String string2) {
		// System.out.println(string1);
		// System.out.println(string2);

		if (string1.equals(string2))
			return true;

		st1 = new StringTokenizer(string1);
		st2 = new StringTokenizer(string2);

		if (st1.countTokens() != st2.countTokens())
			return false;

		for (int i = 0; i < st1.countTokens();) {
			if (!tokenMatching(st1.nextToken(), st2.nextToken())) {
				return false;
			}
		}

		return true;
	}

	boolean tokenMatching(String token1, String token2) {
		// System.out.println(token1+"<->"+token2);
		if (token1.equals(token2))
			return true;
		if (var(token1) && !var(token2))
			return varMatching(token1, token2);
		if (!var(token1) && var(token2))
			return varMatching(token2, token1);
		return false;
	}

	boolean varMatching(String vartoken, String token) {
		if (vars.containsKey(vartoken)) {
			if (token.equals(vars.get(vartoken))) {
				return true;
			} else {
				return false;
			}
		} else {
			vars.put(vartoken, token);
		}
		return true;
	}

	boolean var(String str1) {
		return str1.startsWith("?");
	}

}
